﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BrightIdeasSoftware;
using ControlsLib.Filters;
using FrameworkLib.Facades.Paging;
using FrameworkLib.Filters;

namespace ControlsLib
{
    [Serializable]
    public partial class AnagraficaManagerObjectListView<T> : Form, IForm where T : class, new()
    {
        public event EventHandler<CustomEventArgs<T>> ButtonClicked;
        public event EventHandler<CustomEventArgs<T>> CustomButtonClicked;
        public event EventHandler<CustomEventArgs<T>> ItemSelected;

        ButtonsBar<T> m_buttonsBar = null;
        bool m_canModify = false;
        T m_current = default(T);
        private OLVColumn[] m_filterColumns = null;
        System.Security.Principal.GenericPrincipal m_principal = null;
        object m_popupContainer = null;
        bool m_useFilter = false;
        bool m_isFiltering = false;
        bool m_allowNormalButtonManagment = false;
        bool m_showFilterTracing = false;
        IFilterContainerBase<IFilterBase> m_filter = null;

        public IFilterContainerBase<IFilterBase> Filter
        {
            get { return m_filter; }
            set 
            { 
                m_filter = value;

                if (m_filter != null)
                {
                    m_filter.ExecuteFilter += new EventHandler(m_filter_ExecuteFilter);
                }
            }
        }

        public bool ShowFilterTracing
        {
            get { return m_showFilterTracing; }
            set { m_showFilterTracing = value; }
        }

        public string FilterTraceText
        {
            get { return this.dynLblFilterTrace.Text; }
            set { this.dynLblFilterTrace.Text = value; }
        }

        public bool AllowNormalButtonManagment
        {
            get { return m_allowNormalButtonManagment; }
            set { m_allowNormalButtonManagment = value; }
        }

        protected internal bool IsFiltering
        {
            get { return m_isFiltering; }
            set 
            { 
                m_isFiltering = value;

                if (this.Pager != null) this.Pager.ResetSettings();
            }
        }

        public bool UseFilter
        {
            get { return m_useFilter; }
            set 
            { 
                m_useFilter = value;

                this.m_buttonsBar.ShowFilterButton = value;
            }
        }

        public object PopupContainerControl
        {
            get { return m_popupContainer; }
            set
            {
                m_popupContainer = value;

                if (m_useFilter && (m_popupContainer != null))
                {
                    this.m_buttonsBar.GetFilterControl().TheContainer = m_popupContainer;
                }
            }
        }

        public bool ShowPager 
        {
            get { return this.m_buttonsBar.ShowPager; }
            set { this.m_buttonsBar.ShowPager = value; } 
        }

        public IPager Pager
        {
            get { return this.m_buttonsBar.GetPager(); }
        }

        public bool ShowOnlyCustomButton
        {
            get { return this.m_buttonsBar.ShowOnlyCustomButton; }
            set { this.m_buttonsBar.ShowOnlyCustomButton = value; }
        }

        public OLVColumn[] FilterColumns
        {
            get { return m_filterColumns; }
            set 
            { 
                m_filterColumns = value;

                if (m_filterColumns != null)
                {
                    this.objectListView1.UseFiltering = true;
                }
            }
        }

        public T Current
        {
            get { return m_current; }
            set { m_current = value; }
        }

        public bool CanModify
        {
            get { return m_canModify; }
            set 
            { 
                m_canModify = value;
            }
        }

        public System.Security.Principal.IPrincipal Principal
        {
            get { return System.Threading.Thread.CurrentPrincipal; }
        }

        public AnagraficaManagerObjectListView()
        {
            InitializeComponent();
        }

        public virtual void InitializeForm()
        {
            if (!this.DesignMode)
            {
                m_buttonsBar = new ButtonsBar<T>();
                m_buttonsBar.Dock = DockStyle.Bottom;
                this.Controls.Add(m_buttonsBar);

                m_buttonsBar.ButtonClicked += new EventHandler<CustomEventArgs<T>>(m_buttonsBar_ButtonClicked);
                m_buttonsBar.CustomButtonClicked += new EventHandler<CustomEventArgs<T>>(m_buttonsBar_CustomButtonClicked);
                this.objectListView1.ItemsChanged += new EventHandler<ItemsChangedEventArgs>(objectListView1_ItemsChanged);

                ShowPager = false;
            }
        }

        void gestionePolveriObjectListView1_SelectionChanged(object sender, EventArgs e)
        {
            ManageSelection(sender);
        }

        public void SetupDataGridEvents()
        {
            this.objectListView1.SelectionChanged += new EventHandler(gestionePolveriObjectListView1_SelectionChanged);
        }

        void objectListView1_ItemsChanged(object sender, ItemsChangedEventArgs e)
        {
            SetupDataGridEvents();
        }

        public void ClearDataGridEvents()
        {
            this.objectListView1.SelectionChanged -= new EventHandler(gestionePolveriObjectListView1_SelectionChanged);
        }

        protected void SetGridItemSelected(int index)
        {
            if ((this.objectListView1.Items.Count > 0) && (index >= 0))
            {
                this.objectListView1.SelectionChanged -= new EventHandler(gestionePolveriObjectListView1_SelectionChanged);
                
                this.objectListView1.SelectedIndex = index;
                
                m_buttonsBar.CurrentAction = Actions.ItemSelected;

                this.objectListView1.SelectionChanged += new EventHandler(gestionePolveriObjectListView1_SelectionChanged);
            }
        }

        void m_filter_ExecuteFilter(object sender, EventArgs e)
        {
            throw new NotImplementedException();
        }

        public void ManageFilter(CheckBox chk, OLVColumn column)
        {
            switch (chk.CheckState)
            {
                case CheckState.Checked:
                    AddFilter(column);
                    break;
                case CheckState.Indeterminate:
                    break;
                case CheckState.Unchecked:
                    RemoveFilter(column);
                    break;
                default:
                    break;
            }
        }

        public bool AddFilter(OLVColumn column)
        {
            bool retValue = false;

            if (m_filterColumns == null)
            {
                m_filterColumns = new OLVColumn[0];
            }

            if (m_filterColumns != null)
            {
                if ((m_filterColumns.Length == 1) && (m_filterColumns[0] == null))
                {
                    m_filterColumns.SetValue(column, 0);
                }
                else 
                {
                    Array.Resize(ref m_filterColumns, m_filterColumns.Length + 1);
                    m_filterColumns.SetValue(column, m_filterColumns.Length - 1);
                }

                //this.objectListView1.UseFiltering = true;
                retValue = true;
            }

            return retValue;
        }

        public bool RemoveFilter(OLVColumn column)
        {
            bool retValue = false;

            if (m_filterColumns != null)
            {
                if (m_filterColumns.Contains(column))
                {
                    int index = Array.IndexOf(m_filterColumns, column);
                    if (index != -1)
                    {
                        Array.Clear(m_filterColumns, index, 1);
                        Array.Resize(ref m_filterColumns, m_filterColumns.Length-1);

                        if ((m_filterColumns.Length == 0) || ((m_filterColumns.Length == 1) && (m_filterColumns[0] == null)))
                        {
                            //this.objectListView1.UseFiltering = false;
                            m_filterColumns = null;
                        }

                        retValue = true;                        
                    }
                }
            }

            return retValue;
        }

        void m_buttonsBar_CustomButtonClicked(object sender, CustomEventArgs<T> e)
        {
            this.InitializeButtonBar();

            if (e.ButtonName=="btnDelete" && e.Item !=null)
                if (MessageBox.Show("Stai per cancellare l'elemento.\n\rVuoi Proseguire ?", "Gestione Polveri",
                            MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.No)
                {
                    e.Action = Actions.Unselected;
                }
            if (e.ButtonName == "btnDelete" && e.Item == null)
                MessageBox.Show("Per cancellare un movimento è necessario selezionarlo.");
            {
                    e.Action = Actions.Unselected;
                }

            if (CustomButtonClicked != null)
            {
                CustomButtonClicked(sender, e);
            }
        }

        void m_buttonsBar_ButtonClicked(object sender, CustomEventArgs<T> e)
        {
            switch (e.Action)
            {
                case Actions.Unselected:
                    break;
                case Actions.Add:
                    m_buttonsBar.CurrentAction = Actions.Unselected;
                    break;
                case Actions.Modify:
                    break;
                case Actions.Delete:
                    {
                        if(MessageBox.Show("Stai per cancellare l'elemento.\n\rVuoi Proseguire ?", "Gestione Polveri", 
                            MessageBoxButtons.YesNo, MessageBoxIcon.Question)== System.Windows.Forms.DialogResult.No)
                        {
                            e.Action = Actions.Unselected;
                        }
                    }
                    break;
                case Actions.Confirm:
                    this.Close();
                    break;
                case Actions.Cancel:
                    if(m_allowNormalButtonManagment)
                        m_buttonsBar.CurrentAction = Actions.New;
                    else
                        m_buttonsBar.CurrentAction = Actions.Unselected;

                    this.ClearControls(this.Controls);
                    break;
                case Actions.New:
                    if(m_allowNormalButtonManagment)
                        m_buttonsBar.CurrentAction = Actions.Add;
                    //ClearDataGridEvents();
                    break;
                default:
                    break;
            }

            if (ButtonClicked != null)
            {
                ButtonClicked(sender, e);
            }
        }

        void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            ManageSelection(sender);
        }

        void RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            ManageSelection(sender);
        }

        private void ManageSelection(object sender)
        {
            if (((ObjectListView)sender).SelectedObject != null)
            {
                m_buttonsBar.Item = (T)((ObjectListView)sender).SelectedObject;
                if (m_buttonsBar.CurrentAction != Actions.Add)
                {
                    if (!ShowOnlyCustomButton)
                        m_buttonsBar.CurrentAction = (m_canModify ? Actions.Delete | Actions.Modify : Actions.Delete);
                    else
                    {
                        if (ShowOnlyCustomButton && m_canModify)
                            m_buttonsBar.CurrentAction = (m_canModify ? Actions.Delete | Actions.Modify : Actions.Delete);
                    }
                }
                else
                {
                    //this.dataGridView1.ClearSelection();
                    //this.dataGridView1.CurrentCell = null;
                }

                m_current = m_buttonsBar.Item;

                if (ItemSelected != null)
                {
                    ItemSelected(sender, new CustomEventArgs<T>(m_buttonsBar.CurrentAction, m_buttonsBar.Item));
                }
                //this.propertyGrid1.SelectedObject = m_buttonsBar.Item;
            }
        }

        protected void ResetButtons()
        {
            m_buttonsBar.CurrentAction = Actions.Unselected;
        }

        protected void SetButtonsBar(Actions action)
        {
            m_buttonsBar.CurrentAction = action;
        }

        protected void ClearControls(Control.ControlCollection controls)
        {
            foreach (Control c in controls)
            {
                if (c.Controls.Count > 0)
                {
                    ClearControls(c.Controls);
                }
                else
                {
                    if (c.Name.StartsWith("dyn"))
                    {
                        c.Text = string.Empty;
                    }
                }
            }
        }

        protected void SelectComboItem(ComboBox comboBox, string item)
        {
            comboBox.SelectedIndex = comboBox.FindString(item);
        }

        private void dyntxtFindBox_TextChanged(object sender, EventArgs e)
        {
            //TextMatchFilter filtroColore = TextMatchFilter.Contains(this.objectListView1, dyntxtFindBox.Text);
            TextMatchFilter filtroColore = TextMatchFilter.Contains(this.objectListView1, string.Empty);
            filtroColore.Columns = m_filterColumns;
            this.objectListView1.ModelFilter = filtroColore;

            if (m_filterColumns != null)
            {
                if (m_filterColumns.Length > 0)
                {
                    this.objectListView1.UseFiltering = true;
                }
                else
                {
                    this.objectListView1.UseFiltering = false;
                }
            }
        }

        public void AddCustomButton(string name, string text)
        {
            this.m_buttonsBar.AddCustomButton(name, text);
        }

        public void EnableButton(string name, bool enable)
        {
            this.m_buttonsBar.EnableButton(name, enable);
        }

        public Button GetCustomButton(string name)
        {
            return this.m_buttonsBar.GetCustomButton(name);
        }

        public void InitializeButtonBar()
        {
            this.m_buttonsBar.InitializeButtonBar();
        }
    }
}
